#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QNetworkDatagram>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //创建出这个实例
    socket = new QUdpSocket(this);//放在对象书上，不需要手动delete
    this->setWindowTitle("服务器");
    // 连接信号槽
    connect(socket, &QUdpSocket::readyRead, this, &Widget::processResquest);
    // 绑定端口号
    bool ret = socket->bind(QHostAddress::Any, 9090);
    if(!ret)
    {
        //绑定失败
        QMessageBox::critical(this, "服务器启动出错", socket->errorString());//非法？被占用？...
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

//这个函数完成的逻辑，就是服务器的最核心逻辑了
void Widget::processResquest()
{
    //1. 读取请求并解析
    const QNetworkDatagram& requestDatagram = socket->receiveDatagram();
    QString request = requestDatagram.data();
    //2. 根据请求计算相应
    const QString& response =  process(request);
    //3. 将响应协会客户端
    QNetworkDatagram responseDatagram(response.toUtf8(), requestDatagram.senderAddress(), requestDatagram.senderPort());
    socket->writeDatagram(responseDatagram);
    // 显示到页面上
    QString log = "[" + responseDatagram.senderAddress().toString() + ":" + QString::number(requestDatagram.senderPort())
                  + "] req: " + request + ", resp: " + response;
    ui->listWidget->addItem(log);
}

QString Widget::process(const QString &request)
{
    return request;
}
